package jee.boot.module.websocket;

import jee.boot.common.utils.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * web socket 处理器默认实现
 */
public class DefaultWebSocketHandler implements WebSocketHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 新建连接
     *
     * @param session
     * @param sid
     */
    @Override
    public void onOpen(Session session, String sid) {
        logger.debug("建立连接 :"+sid);
        WebSocketSessionManager.addSession(sid,session);
    }

    /**
     * 连接关闭
     *
     * @param session
     * @param sid
     */
    @Override
    public void onClose(Session session, String sid) {
        logger.debug("关闭连接 :"+sid);
        WebSocketSessionManager.removeSession(session);
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 接收消息
     *
     * @param session
     * @param sid
     * @param message
     */
    @Override
    public void onMessage(Session session, String sid, String message) {
        logger.debug("收到消息 :"+sid);
    }

    /**
     * 异常连接
     *
     * @param session
     * @param error
     */
    @Override
    public void onError(Session session, String sid, Throwable error) {
        logger.debug("连接异常 :"+sid+":"+error.getMessage());
        logger.error(error.getMessage(),error);
        WebSocketSessionManager.removeSession(session);
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 发送消息
     *
     * @param message 消息内容
     * @param sid     消息接收人的sid
     */
    @Override
    public void sendMessage(Object message, String sid) {
        List<Session> session = WebSocketSessionManager.getSession(sid);
        sendMessage(session,message);
    }

    /**
     * 广播消息
     *
     * @param message 消息内容
     */
    @Override
    public void sendMessage(Object message) {
       List<Session> session = WebSocketSessionManager.getSessions();
       sendMessage(session,message);
    }
    private void sendMessage(List<Session> session,Object message){
        if(session!=null && !session.isEmpty()){
            Iterator<Session> iterator = session.iterator();
            while (iterator.hasNext()){
                Session next = iterator.next();
                try {
                    next.getBasicRemote().sendText(JsonMapper.toJsonString(message));
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error(e.getMessage(),e);
                }

            }
        }
    }
}
